package com.baidu.translate.demo;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaiduMain {

	// 在平台申请的APP_ID 详见
	// http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
	private static final String APP_ID = "20240122001948319";
	private static final String SECURITY_KEY = "zNbgSg2HRgh6KvpctYZJ";

	public static void main(String[] args) {
		TransApi api = new TransApi(APP_ID, SECURITY_KEY);
		String query = "翻译";
		String transResult = api.getTransResult(query, "auto", "auto");
		System.out.println(unicodeDecode(transResult));
	}

	/**
	 * @Title: unicodeDecode
	 * @Description: unicode解码
	 * @param str
	 * @return
	 */
	public static String unicodeDecode(String string) {
		Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
		Matcher matcher = pattern.matcher(string);
		char ch;
		while (matcher.find()) {
			ch = (char) Integer.parseInt(matcher.group(2), 16);
			string = string.replace(matcher.group(1), ch + "");
		}
		return string;
	}
	
	public static String getTrans(String query) {
		TransApi api = new TransApi(APP_ID, SECURITY_KEY);
		String transResult = api.getTransResult(query, "auto", "auto");
		return unicodeDecode(transResult);
	}

	/**
	 * @Title: unicodeEncode
	 * @Description: unicode编码
	 * @param string
	 * @return
	 */
	public static String unicodeEncode(String string) {
		char[] utfBytes = string.toCharArray();
		String unicodeBytes = "";
		for (int i = 0; i < utfBytes.length; i++) {
			String hexB = Integer.toHexString(utfBytes[i]);
			if (hexB.length() <= 2) {
				hexB = "00" + hexB;
			}
			unicodeBytes = unicodeBytes + "\\u" + hexB;
		}
		return unicodeBytes;
	}


}
